package cn.sciento.boot.api.customize.generator;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import cn.sciento.boot.api.customize.commons.vo.ApiCustomizeRule;
import cn.sciento.boot.api.customize.util.ParamUtil;

public class UrlCodeGenerator extends AbstractCodeGenerator {
  private static final String TYPE = "URL";
  
  public boolean support(String type) {
    return "URL".equalsIgnoreCase(type);
  }
  
  public String generate(ClassPool classPool, CtClass targetClass, CtMethod targetMethod, ApiCustomizeRule rule, boolean returnValue) {
    StringBuilder builder = new StringBuilder();
    builder
      .append("HttpRequestHelper requestHelper = (HttpRequestHelper) cn.sciento.core.convertor.ApplicationContextHelper.getContext().getBean(HttpRequestHelper.class);")
      .append("\r\n")
      .append("org.springframework.http.ResponseEntity responseEntity = ")
      .append("requestHelper.request(\"").append(rule.getTypeValue()).append("\",  org.springframework.http.HttpMethod.POST, ParamUtil.parseParams(\"").append(ParamUtil.parseParamsKey(targetMethod)).append("\", $args));")
      .append("\r\n")
      .append("Object result = responseEntity.getBody();")
      .append("\r\n");
    if (returnValue)
      builder.append("return ($r) result;").append("\r\n"); 
    return builder.toString();
  }
}
